import 'package:flutter/material.dart';
import '../../utils/g.dart';

import 'package:provider/provider.dart';
import '../../providers/order_provider.dart';

import 'confirm/order_bottom_menu.dart';
import 'confirm/user_address.dart';
import 'confirm/user_coupon.dart';
import 'confirm/order_remark.dart';
import 'confirm/user_score.dart';
import 'confirm/order_price.dart';

class OrderConfirm extends StatefulWidget {
  String cartId;
  int isNew = 0;
  OrderConfirm({Key? key, required String this.cartId, int this.isNew = 0}) : super(key: key);

  @override
  _OrderConfirmState createState() => _OrderConfirmState();
}

class _OrderConfirmState extends State<OrderConfirm> {
  var _futureInstance;
  Map order = {};

  var trailingIcon = const Icon(
    Icons.chevron_right,
    size: 24,
    color: Colors.grey
  );

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _futureInstance = G.api.order.confirm(widget.cartId, widget.isNew);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('订单确认'),
        centerTitle: true,
      ),
      body: FutureBuilder(
        future: _futureInstance,
        builder: (context, snapshot) {
          // print('FutureBuilder - builder');
          if (snapshot.hasData) {
            var res = snapshot.data as Map;
            if (res['status'] == 200) {
              order = res['data'];

              // 初始化订单状态
              Provider.of<OrderProvider>(context, listen: false).initOrder(order);
              // 初始化订单价格
              Provider.of<OrderProvider>(context, listen: false).setOrderPrice();

              return Stack(
                children: [
                  ListView(
                    children: [
                      // 收获地址
                      const UserAddress(),

                      // 商品列表
                      _getProductList(),

                      // 优惠券
                      const UserCoupon(),

                      // 积分抵扣
                      const UserScore(),

                      // 订单备注
                      const OrderRemark(),

                      // 订单价格明细
                      const OrderPrice()
                    ],
                  ),
                  const Positioned(
                    bottom: 0,
                    left: 0,
                    child: OrderBottomMenu()
                  )
                ],
              );
            } else {
              // 报错
              // 跳转到登录页
              Future.delayed(const Duration(milliseconds: 500), () {
                G.router.navigateTo(context, '/cart');
              });
            }
          } else if (snapshot.hasError) {
            return Center(
              child: Text("${snapshot.error}"),
            );
          }

          return G.loader();
        }
      ),
    );
  }

  Widget _getProductList() {
    return Wrap(
      spacing: 10.0,
      direction: Axis.horizontal,
      alignment: WrapAlignment.start,
      children: List<Widget>.generate(
        order['cartInfo'].length, (int index) {
          return Container(
            padding: const EdgeInsets.fromLTRB(10, 10, 10, 15),
            child: ListTile(
              isThreeLine: true,
              onTap: () {
                Map<String, dynamic> p = {
                  'id': order['cartInfo'][index]['product_id']
                };
                G.router.navigateTo(context, '/product_detail'+G.parseQuery(params: p));
              },
              leading: G.imageWidget(
                order['cartInfo'][index]['productInfo']['image'],
                width: 100,
                height: 100
              ),
              title: Text(
                order['cartInfo'][index]['productInfo']['store_name'].toString(),
                style: const TextStyle(
                  fontSize: 16,
                ),
                overflow: TextOverflow.ellipsis,
              ),
              subtitle: Column(
                children: [
                  Container(
                    width: 200,
                    child: Text(
                      order['cartInfo'][index]['productInfo']['attrInfo']['sku'],
                      style: const TextStyle(
                        fontSize: 16,
                      ),
                      overflow: TextOverflow.ellipsis,
                      textAlign: TextAlign.left,
                    ),
                  ),
                  Row(
                    children: [
                      Text(
                        "￥ "+order['cartInfo'][index]['truePrice'].toString(),
                        style: TextStyle(
                          fontSize: 16,
                          color: Theme.of(context).primaryColor,
                          fontWeight: FontWeight.w500
                        ),
                        overflow: TextOverflow.ellipsis,
                      ),
                      Text(
                        " X "+order['cartInfo'][index]['cart_num'].toString()
                      )
                    ],
                  )
                ],
              ),
              trailing: trailingIcon,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10),
                side: BorderSide(
                  color: Colors.grey.shade400,
                  width: 1
                )
              ),
            )
          );
        }
      ).toList(),
    );
  }
}